package kingwing.dc.core.view.frame.main.register.excelmodel;

import java.util.Collection;
import java.util.List;

import kingwing.dc.core.view.frame.main.register.menu.AbstractMenuGenerator;

import org.hibernate.Session;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.CoreHibernateDao;
import com.bstek.bdf2.core.orm.hibernate.ISessionCallback;
import com.bstek.bdf2.importexcel.model.ExcelModel;
import com.bstek.bdf2.importexcel.model.ExcelModelDetail;

@Component
public class SystemInitExcelController extends CoreHibernateDao implements
		InitializingBean, ApplicationContextAware {

	private ApplicationContext applicationContext;

	@Override
	public void afterPropertiesSet() throws Exception {

		this.doInHibernateSession(new ISessionCallback<Object>() {

			@Override
			public Object doInSession(Session session) {

				Number num = (Number) session.createQuery(
						"select count(*) from " + ExcelModel.class.getName())
						.uniqueResult();

				if (num.intValue() == 0) {

					Collection<AbstractExcleGenerator> generators = applicationContext
							.getBeansOfType(AbstractExcleGenerator.class)
							.values();

					if (generators != null) {
						for (AbstractExcleGenerator amg : generators) {
							List<ExcelModel> ExcelModels = amg.getExcelModels();
							if (ExcelModels != null && ExcelModels.size() > 0) {
								for (ExcelModel excelModel : ExcelModels) {
									List<ExcelModelDetail> excelModelDetails = excelModel
											.getListExcelModelDetail();
									session.save(excelModel);
									if (excelModelDetails != null
											&& excelModelDetails.size() > 0) {
										for (ExcelModelDetail excelModelDetail : excelModelDetails) {
											session.save(excelModelDetail);
										}
									}
								}
							}
						}
					}

				}

				return null;
			}
		});

	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		super.setApplicationContext(applicationContext);
		this.applicationContext = applicationContext;
	}

}
